package cn.lj.controller;


import cn.hutool.core.map.MapUtil;
import cn.lj.entity.Menu;
import cn.lj.entity.RoleMenu;
import cn.lj.entity.User;
import cn.lj.response.Result;
import cn.lj.service.MenuService;
import cn.lj.service.RoleMenuService;
import cn.lj.service.UserService;
import cn.lj.vo.MenuDto;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 李津
 * @since 2021-05-19
 */
@RestController
@RequestMapping("/sys/menu")
@Api(value = "系统菜单模块",tags = "系统菜单接口")
public class MenuController {

    private final MenuService menuService;

    private final UserService userService;

    private final RoleMenuService roleMenuService;
    @Autowired
    public MenuController(MenuService menuService, UserService userService, RoleMenuService roleMenuService) {
        this.menuService = menuService;
        this.userService = userService;
        this.roleMenuService = roleMenuService;
    }

    /**
     * 当前用户的菜单和权限信息
     * @param principal
     * @return
     */
    @GetMapping("/nav")
    @ApiOperation(value = "获取菜单和权限信息",notes = "当前用户的菜单和权限信息")
    public Result nav(Principal principal) {
        //Principal principal表示注入当前用户的信息，getName就可以获取当当前用户的用户名了
        User sysUser = userService.getByUserName(principal.getName());

        // 获取权限信息
        String authorityInfo = userService.getUserAuthorityInfo(sysUser.getId());// ROLE_admin,ROLE_normal,sys:user:list,....
        String[] authorityInfoArray = StringUtils.tokenizeToStringArray(authorityInfo, ",");

        // 获取导航栏信息
        List<MenuDto> navs = menuService.getCurrentUserNav(sysUser);

        Map<Object, Object> data = MapUtil.builder()
                .put("authoritys", authorityInfoArray)
                .put("nav", navs)
                .map();

        return Result.ok().data(data);
    }

    /**
     * 获取单个菜单信息
     * @param id
     * @return
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    @ApiOperation(value = "获取单个菜单信息",notes = "获取单个菜单信息")
    public Result info(@PathVariable(name = "id") Long id) {
        return Result.ok().data(menuService.getById(id));
    }

    /**
     * 获取所有菜单信息
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    @ApiOperation(value = "获取所有菜单信息",notes = "获取所有菜单信息")
    public Result list() {
        List<Menu> menus = menuService.tree();
        return Result.ok().data(menus);
    }

    /**
     * 新建菜单
     * @param sysMenu
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    @ApiOperation(value = "新建菜单",notes = "新建菜单")
    public Result save(@Validated @RequestBody Menu sysMenu) {

        sysMenu.setCreated(LocalDateTime.now());

        menuService.save(sysMenu);
        return Result.ok();
    }

    /**
     * 修改菜单
     * @param sysMenu
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    @ApiOperation(value = "修改菜单",notes = "修改菜单")
    public Result update(@Validated @RequestBody Menu sysMenu) {

        sysMenu.setUpdated(LocalDateTime.now());

        menuService.updateById(sysMenu);

        // 清除所有与该菜单相关的权限缓存
        userService.clearUserAuthorityInfoByMenuId(sysMenu.getId());
        return Result.ok();
    }

    /**
     * 删除菜单
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    @ApiOperation(value = "删除菜单",notes = "删除菜单")
    @Transactional
    public Result delete(@PathVariable("id") Long id) {

        int count = menuService.count(new QueryWrapper<Menu>().eq("parent_id", id));
        if (count > 0) {
            return Result.fail("请先删除子菜单");
        }

        // 清除所有与该菜单相关的权限缓存r
        userService.clearUserAuthorityInfoByMenuId(id);

        menuService.removeById(id);

        // 同步删除中间关联表
        roleMenuService.remove(new QueryWrapper<RoleMenu>().eq("menu_id", id));
        return Result.ok();
    }
}

